const http = require("http");
const url = require("url");
const querystring = require("querystring");

const server = http.createServer((req, res) => {
  // console.log("有请求进来了");
  let { pathname, query } = url.parse(req.url, true);
  console.log(pathname, "----", query);

  // post
  let arr = [];
  req.on("data", (data) => {
    arr.push(data);
  });
  req.on("end", () => {
    // console.log(Buffer.concat(arr).toString());
    let obj = Buffer.concat(arr).toString();

    // console.log(req.headers["content-type"]);
    if (req.headers["content-type"] === "application/json") {
      let a = JSON.parse(obj);
      // console.log(a);
      a.hobby = "我的昊昊";
      // console.log(a);
      res.end(JSON.stringify(a));
    } else if (
      req.headers["content-type"] === "application/x-www-form-urlencoded"
    ) {
      // console.log("form数据");
      let ret = querystring.parse(obj);
      res.end(JSON.stringify(ret));
    }
  });
});

server.listen(1234, () => {
  console.log("服务已经起来了");
});
